package com.rsstuan.storage.impl;

import java.util.List;


import javax.jdo.PersistenceManager;


import com.rsstuan.data.ArticleData;
import com.rsstuan.data.Channel;
import com.rsstuan.storage.IArticleStorage;
import com.rsstuan.storage.data.ArticleStorageData;

public class GoogleArticleStorage implements IArticleStorage{
	
	@Override
	public ArticleStorageData[] getArticles(Long channelId, int wanted) {
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		String query = "select from " + ArticleStorageData.class.getName()
				+ " where channelId =" + channelId
			    + " order by index desc";
		if (wanted >= 0)
			query += " range 0," + wanted;
		List<ArticleStorageData> articles = (List<ArticleStorageData>) pm.newQuery(query).execute();
		if (articles != null && !articles.isEmpty()) {
			return articles.toArray(new ArticleStorageData[0]);
		}
		else
			return null;
	}
	@Override
	public int saveArticle(ArticleStorageData article) {
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		try {
			pm.makePersistent(article);
			return 1;
		}
		catch (Exception e) {
			return 0;
		}
		finally {
			pm.close();
		}
		
	}
	@Override
	public int saveArticles(ArticleStorageData[] articles) {
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		int newArticle = 0;
		try {
			for (ArticleStorageData article : articles) {
				pm.makePersistent(article);
				newArticle ++;			
			}
			return newArticle;
		}
		catch (Exception e) {
			return newArticle;
		}
		finally {
			pm.close();
			
		}

		
	
	}
	@Override
	public int saveArticles(Channel channel, ArticleData[] articles) {
		ArticleStorageData[] storeData = new ArticleStorageData[articles.length];
		int index = channel.getArticleCount();
		for (int i = 0; i < articles.length; i ++) {
			storeData[i] = new ArticleStorageData();
			storeData[i].setChannelId(channel.getId());
			storeData[i].setIndex(index++);
			storeData[i].setTitle(articles[i].getTitle());
			storeData[i].setLink(articles[i].getLink());
			storeData[i].setAuthor(articles[i].getAuthor());
			storeData[i].setDescription(articles[i].getDescription());
			storeData[i].setPubDate(articles[i].getPubDate());
			storeData[i].setDigest(articles[i].getDigest());
			
		}
		return saveArticles(storeData);
	}
}
